var http = require('http');
var path = require('path');
var qs = require('querystring');
var fs = require('fs');
var url = require('url');

//����http client����
var weibo_client = http.createClient(7080,'http://127.0.0.1:7080/apple');

//��ȡ��̬�ļ�
var load_static_file = function(uri,response){
	var filename = path.join(process.cwd(),uri);
	path.exists(filename,function(exists){
		if(!exists){
			response.writeHeader(404,{'Content-Type':'text/plain'});
			response.write('404 Not Found\n');
			response.end();
			return;
		}

		fs.readFile(filename,'binary',function(err,file){
			if(err){
				response.writeHeader(500,{'Content-Type':'text/plain'});
				response.write(err + '\n');
				response.end();
				return;
			}

			response.writeHeader(200);
			response.write(file,'binary');
			response.end();
		});
	});
};

//����http����
var server = http.createServer(function(request,response){
	var uri = url.parse(request.url).pathname;
	var callback = qs.parse(url.parse(request.url).query).callback;
//	console.log(callback);
	if(uri === '/stream'){
	//��ʱ��api�õ���Ҫ�����
	setTimeout(function(){
		var client_request = weibo_client.request('GET','http://127.0.0.1:7080/apple/saveLogin.htm',{'host':'http://127.0.0.1:7080/apple'});
		//�Է��ص���ݽ��д���
		client_request.on('response',function(res){
			var body = '';
			res.on('data',function(data){
				body += data;
			});

			res.on("end",function(){
				var weibo = JSON.parse(body);
				if(weibo.length > 0){
					response.writeHead(200,{'Content-Type':'text/javasript'});
					var text = callback + "("+JSON.stringify(weibo)+")";
					//console.log(text);
					response.write(text);
					response.end();
				}
			});
		});
		client_request.end();
	},5000);
	}else{
		load_static_file(uri,response);
	}
});

server.listen(8000);
